package com.credithc.customers.manager.service.impl;

import com.credithc.baseserv.core.service.impl.BaseServiceImpl;
import com.credithc.baseserv.core.utils.DateTimeUtils;
import com.credithc.baseserv.pageHelper.PageInfo;
import com.credithc.customers.base.codes.CustomerCodes;
import com.credithc.customers.base.constants.CustomerConstants;
import com.credithc.customers.base.exception.CustomerException;
import com.credithc.customers.base.factory.DictionaryFactory;
import com.credithc.customers.base.mapper.BizModifyMapper;
import com.credithc.customers.base.mapper.CustomerAbnormalMapper;
import com.credithc.customers.base.mapper.CustomerIdInfoMapper;
import com.credithc.customers.base.mapper.CustomerMergeFlowMapper;
import com.credithc.customers.base.po.BizModifyPo;
import com.credithc.customers.base.po.CustomerAbnormalPo;
import com.credithc.customers.base.po.CustomerIdInfoPo;
import com.credithc.customers.base.po.CustomerMergeFlowPo;
import com.credithc.customers.base.service.ICacheService;
import com.credithc.customers.base.service.ICommonService;
import com.credithc.customers.base.utils.ClassUtils;
import com.credithc.customers.manager.mapper.BizMonitorMapper;
import com.credithc.customers.manager.ro.BizModifyRo;
import com.credithc.customers.manager.ro.CustomerAbnormalRo;
import com.credithc.customers.manager.service.DesensitizationService;
import com.credithc.customers.manager.service.IBizMonitorService;
import com.credithc.customers.manager.vo.BizModifyVo;
import com.credithc.customers.manager.vo.CustomerAbnormalVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.sql.Timestamp;
import java.util.*;

/**
 * @Title: 业务监控处理
 * @Author: Denghx
 * @Date: 2018/12/18 11:16
 * @Description: com.credithc.customers.manager.service.impl
 * @Version: V1.0.0
 */
@Service
@Slf4j
public class BizMonitorServiceImpl extends BaseServiceImpl<BizModifyPo, BizModifyRo, BizModifyVo> implements IBizMonitorService {
    @Autowired
    private ICommonService commonService;
    @Autowired
    private CustomerAbnormalMapper abnormalMapper;
    @Autowired
    private CustomerIdInfoMapper customerIdInfoMapper;
    @Autowired
    private BizModifyMapper bizMapper;
    @Autowired
    private CustomerMergeFlowMapper customerMergeFlowMapper;
    @Autowired
    private DesensitizationService desensitizationService;
    @Autowired
    private ICacheService cacheService;
    @Autowired
    private BizMonitorMapper bizMonitorMapper;

    @Override
    public PageInfo<BizModifyVo> getBizInfo(BizModifyRo ro) {
        try {
            Example example = new Example(BizModifyPo.class);
            Example.Criteria criteria = example.createCriteria();
            example.setOrderByClause("create_time desc");
            if (StringUtils.isNotEmpty(ro.getCustomerNo())) {
                criteria.andEqualTo("customerNo", ro.getCustomerNo());
            }
            if (StringUtils.isNotEmpty(ro.getCustomerName())) {
                criteria.andEqualTo("customerName", ro.getCustomerName());
            }
            if (StringUtils.isNotEmpty(ro.getIdCardNo())) {
                criteria.andEqualTo("idCardNo", ro.getIdCardNo());
            }
            if (StringUtils.isNotEmpty(ro.getStatus())) {
                criteria.andEqualTo("status", ro.getStatus());
            }
            if (StringUtils.isNotEmpty(ro.getNoticeStatus())) {
                criteria.andEqualTo("noticeStatus", ro.getNoticeStatus());
            }
            if (StringUtils.isNotEmpty(ro.getSubSystemSign())) {
                criteria.andEqualTo("subSystemSign", ro.getSubSystemSign());
            }
            if (StringUtils.isNotBlank(ro.getCreateTimeStart()) && StringUtils.isNotBlank(ro.getCreateTimeEnd())) {
                criteria.andBetween("createTime", ro.getCreateTimeStart(), ro.getCreateTimeEnd());
            } else if (StringUtils.isNotBlank(ro.getCreateTimeStart())) {
                criteria.andGreaterThanOrEqualTo("createTime", ro.getCreateTimeStart());
            } else if (StringUtils.isNotBlank(ro.getCreateTimeEnd())) {
                criteria.andLessThanOrEqualTo("createTime", ro.getCreateTimeEnd());
            }
            if (StringUtils.isNotBlank(ro.getUpdateTimeStart()) && StringUtils.isNotBlank(ro.getUpdateTimeEnd())) {
                criteria.andBetween("updateTime", ro.getUpdateTimeStart(), ro.getUpdateTimeEnd());
            } else if (StringUtils.isNotBlank(ro.getUpdateTimeStart())) {
                criteria.andGreaterThanOrEqualTo("updateTime", ro.getUpdateTimeStart());
            } else if (StringUtils.isNotBlank(ro.getUpdateTimeEnd())) {
                criteria.andLessThanOrEqualTo("updateTime", ro.getUpdateTimeEnd());
            }
            PageInfo<BizModifyPo> pageInfo = this.queryPageResultByExample(example, ro.getPageNo(), ro.getPageSize());
            desensitizationService.desensitizationList(pageInfo.getList());
            List<BizModifyVo> vos = new ArrayList<>();
            if (pageInfo.getTotalCount() > 0) {
                for (BizModifyPo po : pageInfo.getList()) {
                    BizModifyVo vo = new BizModifyVo();
                    BeanUtils.copyProperties(po, vo);
                    if (po.getCreateTime() != null) {
                        vo.setCreateTime(DateTimeUtils.dateToStrLong(po.getCreateTime()));
                    }
                    if (po.getUpdateTime() != null) {
                        vo.setUpdateTime(DateTimeUtils.dateToStrLong(po.getUpdateTime()));
                    }
                    //证件类型
                    Map<String, String> idTypeMap = DictionaryFactory.Dict.ID_TYPE.getDictMap();
                    if (StringUtils.isNotEmpty(po.getIdCardType())) {
                        vo.setIdCardTypeName(idTypeMap.get(po.getIdCardType()));
                    }
                    //通知状态
                    Map<String, String> noticeMap = DictionaryFactory.Dict.NOTICE_STATUS.getDictMap();
                    if (po.getNoticeStatus() != null) {
                        vo.setNoticeStatus(noticeMap.get(po.getNoticeStatus().toString()));
                    }
                    //处理状态
                    Map<String, String> bizMap = DictionaryFactory.Dict.BIZ_STATUS.getDictMap();
                    if (po.getStatus() != null) {
                        vo.setStatus(bizMap.get(po.getStatus().toString()));
                    }
                    //系统标识
                    if (StringUtils.isNotEmpty(po.getSystemSign())) {
                        vo.setSystemSign(cacheService.getSystemNameBySign(po.getSystemSign()));
                    }
                    //子系统标识
                    if (StringUtils.isNotEmpty(po.getSubSystemSign())) {
                        vo.setSubSystemSign(cacheService.getSystemNameBySign(po.getSubSystemSign()));
                    }
                    vos.add(vo);
                }
            }
            return new PageInfo<>(vos, pageInfo.getTotalCount(), ro.getPageNo(), ro.getPageSize());
        } catch (DataAccessException e) {
            log.info("查询业务变更信息报错:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_QUERY);
        }
    }

    @Override
    public PageInfo<CustomerAbnormalVo> selectCustomerAbnormal(CustomerAbnormalRo ro) {
        try {
            Example example = new Example(CustomerAbnormalPo.class);
            Example.Criteria criteria = example.createCriteria();
            example.setOrderByClause("create_time desc");
            if (StringUtils.isNotEmpty(ro.getAbnormalType())) {
                criteria.andEqualTo("abnormalType", ro.getAbnormalType());
            }
            if (StringUtils.isNotEmpty(ro.getCustomerName())) {
                criteria.andEqualTo("customerName", ro.getCustomerName());
            }
            if (StringUtils.isNotEmpty(ro.getIdCardNo())) {
                criteria.andEqualTo("idCardNo", ro.getIdCardNo());
            }
            if (StringUtils.isNotEmpty(ro.getStatus())) {
                criteria.andEqualTo("status", ro.getStatus());
            }
            if (StringUtils.isNotEmpty(ro.getIdCardtype())) {
                criteria.andEqualTo("idCardType", ro.getIdCardtype());
            }
            if (StringUtils.isNotBlank(ro.getCreateTimeStart()) && StringUtils.isNotBlank(ro.getCreateTimeEnd())) {
                criteria.andBetween("createTime", ro.getCreateTimeStart(), ro.getCreateTimeEnd());
            } else if (StringUtils.isNotBlank(ro.getCreateTimeStart())) {
                criteria.andGreaterThanOrEqualTo("createTime", ro.getCreateTimeStart());
            } else if (StringUtils.isNotBlank(ro.getCreateTimeEnd())) {
                criteria.andLessThanOrEqualTo("createTime", ro.getCreateTimeEnd());
            }
            List<CustomerAbnormalVo> vos = new ArrayList<>();
            int count = abnormalMapper.selectCountByExample(example);
            if (count > 0) {
                RowBounds rowBounds = new RowBounds(ro.getPageSize() * (ro.getPageNo() - 1), ro.getPageSize());
                List<CustomerAbnormalPo> pos = abnormalMapper.selectByExampleAndRowBounds(example, rowBounds);
                desensitizationService.desensitizationList(pos);
                for (CustomerAbnormalPo po : pos) {
                    CustomerAbnormalVo vo = new CustomerAbnormalVo();
                    BeanUtils.copyProperties(po, vo);
                    if (po.getCreateTime() != null) {
                        vo.setCreateTime(DateTimeUtils.dateToStrLong(po.getCreateTime()));
                    }
                    //处理状态
                    Map<String, String> processMap = DictionaryFactory.Dict.ABNORMAL_STATUS.getDictMap();
                    if (po.getStatus() != null) {
                        vo.setStatus(processMap.get(po.getStatus().toString()));
                    }
                    //处理状态
                    Map<String, String> abnormalTypeMap = DictionaryFactory.Dict.ABNORMAL_TYPE.getDictMap();
                    if (po.getAbnormalType() != null) {
                        vo.setAbnormalType(abnormalTypeMap.get(po.getAbnormalType().toString()));
                    }
                    //证件类型
                    Map<String, String> idTypeMap = DictionaryFactory.Dict.ID_TYPE.getDictMap();
                    if (StringUtils.isNotEmpty(po.getIdCardType())) {
                        vo.setIdCardType(idTypeMap.get(po.getIdCardType()));
                    }
                    vos.add(vo);
                }
            }
            return new PageInfo<>(vos, count, ro.getPageNo(), ro.getPageSize());
        } catch (DataAccessException e) {
            log.info("查询异常信息报错:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_QUERY);
        }
    }

    @Override
    public Map<String, Object> getAbnormalDetail(String id) {
        Map<String, Object> map = new HashMap();
        List<Map<String, Object>> vos = new ArrayList<>();
        Map<String, Object> vo1 = new HashMap<>();
        CustomerAbnormalPo po = abnormalMapper.selectByPrimaryKey(id);
        desensitizationService.desensitizationObject(po);
        vo1.put("id", po.getId());
        vo1.put("customerNo", po.getCustomerNo());
//        List<String> systemList1 = Arrays.asList(po.getSubSystemSign().split(","));
//        String system1 = "";
//        for (String system : systemList1) {
//            system1 += cacheService.getSystemNameBySign(system) + "  ";
//        }
        //pthb系统标识改造
        String system1 =cacheService.getSystemNameBySign(po.getSubSystemSign());
        vo1.put("subSystemSign", system1);
        vo1.put("customerName", po.getCustomerName());
        vo1.put("idCardType", DictionaryFactory.Dict.ID_TYPE.getDictMap().get(po.getIdCardType()));
        vo1.put("idCardNo", po.getIdCardNo());
        vos.add(vo1);
        String associatedId = po.getAssociatedId();
        List<String> idList = Arrays.asList(associatedId.split(","));
//        Example example = new Example(CustomerIdInfoPo.class);
//        Example.Criteria criteria = example.createCriteria();
//        if (idList.size() > 0) {
//            criteria.andIn("id", idList);
//        }
//        List<CustomerIdInfoPo> pos = customerIdInfoMapper.selectByExample(example);
        //todo pthb subSystemSign
        List<CustomerIdInfoPo> pos =bizMonitorMapper.getAbnormalInfo(idList);
        desensitizationService.desensitizationList(pos);
        if (pos.size() > 0) {
            for (CustomerIdInfoPo idInfoPo : pos) {
                Map<String, Object> vo = new HashMap<>();
                vo.put("customerNo", idInfoPo.getCustomerNo());
//                List<String> systemList = Arrays.asList(idInfoPo.getSubSystemSign().split(","));
//                String subSystemSign = "";
//                for (String system : systemList) {
//                    subSystemSign += cacheService.getSystemNameBySign(system) + "  ";
//                }
                //pthb subSystemSign
                String subSystemSign =cacheService.getSystemNameBySign(idInfoPo.getSubSystemSign());
                vo.put("subSystemSign", subSystemSign);
                vo.put("customerName", idInfoPo.getCustomerName());
                vo.put("idCardType", DictionaryFactory.Dict.ID_TYPE.getDictMap().get(idInfoPo.getIdCardType()));
                vo.put("idCardNo", idInfoPo.getIdCardNo());
                vo.put("id", po.getId());
                vos.add(vo);
            }
        }
        Example example2 = new Example(CustomerMergeFlowPo.class);
        Example.Criteria criteria2 = example2.createCriteria();
        if (idList.size() > 0) {
            criteria2.andIn("mergeId", idList);
        }
        List<CustomerMergeFlowPo> mergeFlowPos = customerMergeFlowMapper.selectByExample(example2);
        desensitizationService.desensitizationList(mergeFlowPos);
        if (mergeFlowPos.size() > 0) {
            for (CustomerMergeFlowPo mergeFlowPo : mergeFlowPos) {
                Map<String, Object> vo2 = new HashMap<>();
                vo2.put("customerNo", mergeFlowPo.getCustomerNo());
                List<String> systemList = Arrays.asList(mergeFlowPo.getSubSystemSign().split(","));
                String system2 = "";
                for (String system : systemList) {
                    system2 += cacheService.getSystemNameBySign(system) + "  ";
                }
                vo2.put("subSystemSign", system2);
                vo2.put("customerName", mergeFlowPo.getCustomerName());
                vo2.put("idCardType", DictionaryFactory.Dict.ID_TYPE.getDictMap().get(mergeFlowPo.getIdCardType()));
                vo2.put("idCardNo", mergeFlowPo.getIdCardNo());
                vo2.put("id", mergeFlowPo.getId());
                vos.add(vo2);
            }
        }
        map.put("list", vos);
        return map;
    }

    @Override
    public void updateAbnormalSts(String id, Integer status) {
        try {
            CustomerAbnormalPo po = new CustomerAbnormalPo();
            po.setId(id);
            if (status.equals(CustomerConstants.ABNORMAL_STATUS_DEAL)) {
                po.setStatus(CustomerConstants.ABNORMAL_STATUS_DEAL);
            } else {
                po.setStatus(CustomerConstants.ABNORMAL_STATUS_NODEAL);
            }
            abnormalMapper.updateByPrimaryKeySelective(po);
        } catch (DataAccessException e) {
            log.info("更新异常信息表异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_UPDATE);
        }
    }

    @Override
    public Map<String, Object> updateBiz(String id) {
        try {
            Map<String, Object> map = new HashMap<>(1);
            BizModifyPo bizPo = this.selectById(id);
            Map<String, Object> newInfo = new HashMap<>(1);
            newInfo.put("customerName", bizPo.getCustomerName());
            newInfo.put("idCardTypeName", DictionaryFactory.Dict.ID_TYPE.getDictMap().get(bizPo.getIdCardType()));
            newInfo.put("idCardType", bizPo.getIdCardType());
            newInfo.put("idCardNo", bizPo.getIdCardNo());
            newInfo.put("id", bizPo.getId());
            newInfo.put("customerNo", bizPo.getCustomerNo());
            //判断三要素是否已存在，存在返回客户号，不存在新增
            CustomerIdInfoPo newIdInfoPo = commonService.getExistCustomerInfo(bizPo.getCustomerName(), bizPo.getIdCardType(), bizPo.getIdCardNo());
            if (newIdInfoPo != null) {
                bizPo.setUpdateTime(new Timestamp(System.currentTimeMillis()));
                bizPo.setStatus(CustomerConstants.BIZ_MODIFY_STATUS_FAIL);
                bizPo.setRemark("变更证件信息已存在");
                bizMapper.updateByPrimaryKeySelective(bizPo);
                throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "变更证件信息已存在，请合并处理，合并客户号为：" + newIdInfoPo.getCustomerNo());
            }
            List<CustomerIdInfoPo> idInfoPos = commonService.getAllCustomer(bizPo.getCustomerNo(), bizPo.getSystemSign(), bizPo.getSubSystemSign());
            desensitizationService.desensitizationList(idInfoPos);
            Map<String, Object> oldInfo = new HashMap<>(1);
            for (CustomerIdInfoPo idInfoPo : idInfoPos) {
                if (idInfoPo.getIdCardType().equals(bizPo.getIdCardType())) {
                    oldInfo.put("customerName", idInfoPo.getCustomerName());
                    oldInfo.put("idCardTypeName", DictionaryFactory.Dict.ID_TYPE.getDictMap().get(idInfoPo.getIdCardType()));
                    oldInfo.put("idCardNo", idInfoPo.getIdCardNo());
                    oldInfo.put("id", idInfoPo.getId());
                }
            }
            if (oldInfo == null || oldInfo.size() < 1) {
                bizPo.setUpdateTime(new Timestamp(System.currentTimeMillis()));
                bizPo.setStatus(CustomerConstants.BIZ_MODIFY_STATUS_FAIL);
                bizPo.setRemark("原证件类型不存在");
                bizMapper.updateByPrimaryKeySelective(bizPo);
                throw new CustomerException(CustomerCodes.PARAM_VALIDATE_ERROR, "证件信息变更失败，原证件类型不存在");
            }
            map.put("newInfo", newInfo);
            map.put("oldInfo", oldInfo);
            return map;
        } catch (DataAccessException e) {
            log.info("查询证件信息异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_QUERY);
        }
    }

    @Override
    public Integer updateBizModify(String bizId, String id, String customerName, String idCardType, String idCardNo, String customerNo) {
        try {
            CustomerIdInfoPo po = new CustomerIdInfoPo();
            CustomerIdInfoPo oldPo = customerIdInfoMapper.selectByPrimaryKey(id);
            po.setId(id);
            po.setCustomerName(customerName);
            po.setIdCardType(idCardType);
            po.setIdCardNo(idCardNo);
            po.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            //更新证件信息表
            int res = customerIdInfoMapper.updateByPrimaryKeySelective(po);
            if (res > 0) {
                //todo 通知相关业务系统
                String oldCustomerName = oldPo.getCustomerName();
                String oldIdCardType = oldPo.getIdCardType();
                String oldIdCardNo = oldPo.getIdCardNo();
                String subSystemSign = oldPo.getSubSystemSign();
                List<String> receiverList = Arrays.asList(StringUtils.split(subSystemSign, ","));
                //通知成功数 失败数
                int succCount = 0;
                for (String receiver : receiverList) {
                    String noticeRes = commonService.sendHttpMsg(receiver, id, customerNo, customerName, idCardType, idCardNo, oldCustomerName, oldIdCardType, oldIdCardNo);
                    if (noticeRes != null && "0".equals(noticeRes)) {
                        succCount++;
                    }
                }
                //修改业务信息变更表状态，状态变为已变更
                BizModifyPo bizPo = new BizModifyPo();
                bizPo.setId(bizId);
                bizPo.setUpdateTime(new Timestamp(System.currentTimeMillis()));
                if (succCount == receiverList.size()) {
                    bizPo.setNoticeStatus(CustomerConstants.NOTICE_STATUS_SUCCESS);
                } else {
                    bizPo.setNoticeStatus(CustomerConstants.NOTICE_STATUS_FAIL);
                }
                bizPo.setStatus(CustomerConstants.BIZ_MODIFY_STATUS_CHANGE);
                bizMapper.updateByPrimaryKeySelective(bizPo);
            }
            return res;
        } catch (DataAccessException e) {
            log.info("更新异常信息表异常:" + ClassUtils.getClassName() + "--" + ClassUtils.getMethodName() + "--" + e.getMessage());
            throw new CustomerException(CustomerCodes.DATABASE_ERROR_UPDATE);
        }
    }

    @Override
    public Map<String, Object> updateAbnormalInfo(String id) {
        Map<String, Object> map = new HashMap();
        List<Map<String, Object>> vos = new ArrayList<>();
        Map<String, Object> vo1 = new HashMap<>();
        CustomerAbnormalPo po = abnormalMapper.selectByPrimaryKey(id);
        vo1.put("id", po.getId());
        vo1.put("customerNo", po.getCustomerNo());
        vo1.put("subSystemSign", po.getSubSystemSign());
        vo1.put("customerName", po.getCustomerName());
        vo1.put("idCardType", DictionaryFactory.Dict.ID_TYPE.getDictMap().get(po.getIdCardType()));
        vo1.put("idCardNo", po.getIdCardNo());
        vos.add(vo1);
        String associatedId = po.getAssociatedId();
        List<String> idList = Arrays.asList(associatedId.split(","));
//        Example example = new Example(CustomerIdInfoPo.class);
//        Example.Criteria criteria = example.createCriteria();
//        if (idList.size() > 0) {
//            criteria.andIn("id", idList);
//        }
//        List<CustomerIdInfoPo> pos = customerIdInfoMapper.selectByExample(example);
        //todo pthb subSystemSign
        List<CustomerIdInfoPo> pos =bizMonitorMapper.getAbnormalInfo(idList);
        if (pos.size() > 0) {
            for (CustomerIdInfoPo idInfoPo : pos) {
                Map<String, Object> vo = new HashMap<>();
                vo.put("id", idInfoPo.getId());
                vo.put("customerNo", idInfoPo.getCustomerNo());
                vo.put("subSystemSign", idInfoPo.getSubSystemSign());
                vo.put("customerName", idInfoPo.getCustomerName());
                vo.put("idCardType", DictionaryFactory.Dict.ID_TYPE.getDictMap().get(idInfoPo.getIdCardType()));
                vo.put("idCardNo", idInfoPo.getIdCardNo());
                vos.add(vo);
            }
        }
        map.put("list", vos);
        return map;
    }

}
